<?php
/**
 * Created by PhpStorm.
 * User: chase
 * Date: 2017/8/29
 * Time: 10:30
 */

namespace app\mobile\controller;

use cmf\controller\AdminBaseController;
use app\educational\model\MessageModel;
use think\Db;

class MessageController extends AdminBaseController
{
    public function index()
    {
        $param = $this->request->param();
        $limit = config('limit_per_page');
        $uid = cmf_get_current_admin_id();

        $where = [
            'm.type' => ['=', 0],  //站内信
            'mu.receive_uid' => ['=', $uid],
            'm.shop_id' => ['=', $this->admin_shop_id],
        ];

        //获取消息列表
        $score_mdl = new MessageModel();
        $data = $score_mdl->getMessages($where, [], $limit, []);

        $this->assign('param', $param);
        $this->assign('messages', $data);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /**
     * 我的消息详情页
     * @return mixed
     */
    public function infoDetail()
    {
        $param = $this->request->param();
        $msg_id = trim($param['msg_id']);
        if (empty($msg_id) || !is_numeric($msg_id)) {
            $this->error('参数错误');
        }
        //当前用户
        $uid = cmf_get_current_admin_id();

        //获取消息
        $where = [
            'm.id' => $msg_id,
            'm.shop_id' => $this->admin_shop_id,
            'mu.receive_uid' => $uid,
        ];
        $msg = Db::name('message_user')->alias('mu')
            ->field('m.*,mu.msg_status')
            ->join('message m', 'm.id=mu.msg_id')
            ->where($where)
            ->find();

        if (count($msg) <= 0) {
            $this->error('没有该信息或信息已删除');
        } else {
            //修改信息已读
            $condition = [
                'msg_id' => $msg_id,
                'receive_uid' => $uid,
            ];
            Db::name('message_user')->where($condition)->update(['msg_status' => 1]);
        }

        $this->assign('message', $msg);
        return $this->fetch();
    }

    public function ajax_read()
    {
        if($this->request->isPost()){
            $param = $this->request->post();
            if(empty($param['msg_id'])){
                $json_data = [
                    'code' => 0,
                    'msg' => '参数有误',
                ];
                return json($json_data);
            }
            //当前用户
            $uid = cmf_get_current_admin_id();
            //修改已读
            $condition = [
                'msg_id' => trim($param['msg_id']),
                'receive_uid' => $uid,
            ];
            Db::name('message_user')->where($condition)->update(['msg_status' => 1]);

            $json_data = [
                'code' => 1,
                'msg' => 'success',
            ];
            return json($json_data);

        }else{
            $json_data = [
                'code' => 0,
                'msg' => '请求错误',
            ];
            return json($json_data);
        }
    }



}